package com.yangtzeu.jwc.activity;

import java.util.Date;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.Toast;

import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.business.AppBusiness;
import com.yangtzeu.jwc.business.MCallBack;
import com.yangtzeu.jwc.business.UpdateBusiness;
import com.yangtzeu.jwc.business.UpdateListener;
import com.yangtzeu.jwc.domain.MyJson;
import com.yangtzeu.jwc.domain.ServerConfig;
import com.yangtzeu.jwc.domain.Student;
import com.yangtzeu.jwc.fragment.IndexFragment;
import com.yangtzeu.jwc.fragment.MoreFragment;
import com.yangtzeu.jwc.fragment.ScoreFragment;
import com.yangtzeu.jwc.fragment.TimetableFragment;
import com.yangtzeu.jwc.fragment.UserFragment;
import com.yangtzeu.jwc.utils.AllActivitys;
import com.yangtzeu.jwc.utils.Common;
import com.yangtzeu.jwc.utils.ConfirmDialog;
import com.yangtzeu.jwc.utils.G;
import com.yangtzeu.jwc.utils.NoticeDialog;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.DataUtil;
import com.zjsx.lib.utils.L;
import com.zjsx.lib.utils.PrefUtil;

public class MainActivity3 extends BaseActivity implements UpdateListener {
    private RadioButton home, score, timetable, user, more;
    private Fragment index_fragment, score_fragment, timetable_fragment, user_fragment, more_fragment;
    public static Student student;
    FragmentManager fragmentManager;
    private ServerConfig sc;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentManager = getFragmentManager();
        switchTab(R.id.home, true);
        //UpdateBusiness ab = new UpdateBusiness(this);
        //ab.update(null);
        config();
    }

    @Override
    public void setView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    public void initActionBar() {
        super.initActionBar();
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.action_logo);
    }

    @Override
    public void initView() {
        super.initView();
        home = (RadioButton) findViewById(R.id.home);
        score = (RadioButton) findViewById(R.id.score);
        timetable = (RadioButton) findViewById(R.id.timetable);
        user = (RadioButton) findViewById(R.id.user);
        more = (RadioButton) findViewById(R.id.more);
    }

    @Override
    public void initListener() {
        super.initListener();
        onItemCheckedChangeListener changeListener = new onItemCheckedChangeListener();
        home.setOnCheckedChangeListener(changeListener);
        score.setOnCheckedChangeListener(changeListener);
        timetable.setOnCheckedChangeListener(changeListener);
        user.setOnCheckedChangeListener(changeListener);
        more.setOnCheckedChangeListener(changeListener);
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
    }

    // 复写点击返回的事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit(new Date());
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        super.onClick(v);
        switch (v.getId()) {
            case R.id.update_cancel:
            case R.id.download_cancel:
                if (sc.version.forceUpdate == 1) {
                    AllActivitys.getInstance().exit();
                }
                break;
            default:
                break;
        }
    }

    // 控制0.5秒以内连点击两次返回才能退出
    // 记录上一次点击的时间
    private Date date = new Date();

    private void exit(Date date) {

        if ((date.getTime() - this.date.getTime()) < (0.8 * 1000)) {
            date = null;
            AllActivitys.getInstance().exit();
        } else {
            Toast.makeText(getApplicationContext(), "再按一次退出程序!", Toast.LENGTH_SHORT).show();
            this.date = date;
        }
    }

    public void setTab(Fragment fragment, boolean isChecked, boolean isAdd) {
        L.d("MainActivity--->" + "isChecked" + isChecked + "isAdd=" + isAdd);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (isAdd) {
            transaction.add(R.id.main_content, fragment);
        } else {
            if (isChecked) {
                transaction.show(fragment);
                // 调用一下isHidden,通知fragment被显示了.
                fragment.isHidden();
            } else {
                transaction.hide(fragment);
            }
        }
        transaction.commit();
    }

    public void switchTab(int id, boolean isChecked) {
        // TODO Auto-generated method stub
        boolean isAdd = false;
        switch (id) {
            case R.id.home:
                if (index_fragment == null) {
                    index_fragment = new IndexFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(index_fragment, isChecked, isAdd);
                break;
            case R.id.score:
                if (score_fragment == null) {
                    score_fragment = new ScoreFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(score_fragment, isChecked, isAdd);
                break;
            case R.id.timetable:
                if (timetable_fragment == null) {
                    timetable_fragment = new TimetableFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(timetable_fragment, isChecked, isAdd);
                break;
            case R.id.user:
                if (user_fragment == null) {
                    user_fragment = new UserFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(user_fragment, isChecked, isAdd);
                break;
            case R.id.more:
                if (more_fragment == null) {
                    more_fragment = new MoreFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(more_fragment, isChecked, isAdd);
                break;
            default:
                break;
        }
    }

    private final class onItemCheckedChangeListener implements OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            L.d("MainActivity--->Tab changed!");
            switchTab(buttonView.getId(), isChecked);
        }

    }

    public void config() {
        if (!PrefUtil.getBoolean(G.IS_INFO_UPLOADED, false)) {
            install();
        } else {
            server();
        }
    }

    private void install() {
        AppBusiness ab = new AppBusiness(this);
        ab.install(new MCallBack() {
            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, MyJson mj) {
                sc = DataUtil.dataToObj(mj.data, ServerConfig.class);
                onConfig();
            }
        });
    }

    private void server() {
        AppBusiness ab = new AppBusiness(this);
        ab.server(new MCallBack() {
            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, MyJson mj) {
                sc = DataUtil.dataToObj(mj.data, ServerConfig.class);
                onConfig();
                L.d(sc.toString());
            }

        });
    }

    private void onConfig() {
        if (sc.close) {
            //此App不在维护
            NoticeDialog.show(this, "通知", sc.message);
            AllActivitys.getInstance().exit();

        } else if (sc.message != null && !"".equals(sc.message.trim()) && !"null".equalsIgnoreCase(sc.message.trim())) {//其它消息
            if (PrefUtil.getInt("messageId", -1) != sc.messageId) {
                if (!NoticeDialog.show(this, "通知", sc.message)) {
                    PrefUtil.setInt("messageId", sc.messageId);
                }
            }
        }
        UpdateBusiness ub = new UpdateBusiness(MainActivity3.this, MainActivity3.this);
        if (ub.checkVersion(sc.version)) {
            ub.haveNewVersion(sc.version);
        }
    }

    @Override
    public void cancelUpdate() {
        // TODO Auto-generated method stub
        if (sc.version.forceUpdate == 1) {
            AllActivitys.getInstance().exit();
        }
    }

    @Override
    public void cancelDownload() {
        // TODO Auto-generated method stub
        if (sc.version.forceUpdate == 1) {
            AllActivitys.getInstance().exit();
        }
    }

    @Override
    public void cancelDownloadFromExplorer() {
        // TODO Auto-generated method stub
        if (sc.version.forceUpdate == 1) {
            AllActivitys.getInstance().exit();
        }
    }

    @Override
    public void downloadFromExplorer() {
        // TODO Auto-generated method stub
        AllActivitys.getInstance().exit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public RadioButton getHome() {
        return home;
    }

    public void setHome(RadioButton home) {
        this.home = home;
    }

    public RadioButton getScore() {
        return score;
    }

    public void setScore(RadioButton score) {
        this.score = score;
    }

    public RadioButton getTimetable() {
        return timetable;
    }

    public void setTimetable(RadioButton timetable) {
        this.timetable = timetable;
    }

    public RadioButton getUser() {
        return user;
    }

    public void setUser(RadioButton user) {
        this.user = user;
    }

    public RadioButton getMore() {
        return more;
    }

    public void setMore(RadioButton more) {
        this.more = more;
    }
}